#include "font.hpp"
#include "log.hpp"

namespace sdl_engine {

Font::Font(const std::string& filename, int pt) {
    font_ = TTF_OpenFont(filename.c_str(), pt);
    if (!font_) {
        Loge(Fmt("create font failed: %s", TTF_GetError()));
    } else {
        pt_ = pt;
    }
}

Font::~Font() {
    TTF_CloseFont(font_);
}

Size Font::GetUTF8Size(const std::string& text) const {
    Size size;
    TTF_SizeUTF8(font_, text.c_str(), &size.w, &size.h);
    return size;
}

Size Font::GetTextSize(const std::string& text) const {
    Size size;
    TTF_SizeText(font_, text.c_str(), &size.w, &size.h);
    return size;
}


TextTexture::TextTexture(Font& font): font_(font) {}

void TextTexture::SetText(const std::string& text) {
    if (text != str_ || text.empty()) {
        texture_.reset(nullptr);
        str_ = text;
    }
}

void TextTexture::TryGenTexture() {
    if (!texture_ && !str_.empty()) {
        auto surface = TTF_RenderUTF8_Blended(font_.Raw(),
                                              str_.c_str(),
                                              {255, 255, 255, 255});
        if (!surface) {
            Logw(Fmt("blend font surface failed: %s", TTF_GetError()));
        } else {
            texture_.reset(new Texture(surface));
            SDL_FreeSurface(surface);
        }
    }
}

}
